/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iodegree.lib.quadro;

import iodegree.lib.MyTableModel;
import iodegree.lib.CommonsLib;
import iodegree.lib.StatisticsConversion;
import iodegree.lib.pattern.*;
import java.io.File;
import javax.swing.JFileChooser;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

/**
 *
 * @author Libra
 */
public class ConnIOUI extends javax.swing.JFrame {

    /**
     * Creates new form SplitUI
     */
    public ConnIOUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        DataFileChooser = new javax.swing.JFileChooser();
        btnGrp = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        btnGenRndM2 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        btnOpenDatabase = new javax.swing.JButton();
        lblOpenDatabase = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtCycles = new javax.swing.JTextField();
        btnOpenDbDefault = new javax.swing.JButton();
        rdoBoth = new javax.swing.JRadioButton();
        rdoGluOnly = new javax.swing.JRadioButton();
        rdoGABAOnly = new javax.swing.JRadioButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        statsPanel = new javax.swing.JScrollPane();
        statsTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnGenRndM2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnGenRndM2.setText("Generate Random");
        btnGenRndM2.setEnabled(false);
        btnGenRndM2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenRndM2ActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText("Random Sim :");

        btnOpenDatabase.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDatabase.setText("Open");
        btnOpenDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDatabaseActionPerformed(evt);
            }
        });

        lblOpenDatabase.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblOpenDatabase.setText("Open Database File :");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel8.setText("Cycles");

        txtCycles.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtCycles.setText("1000");
        txtCycles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCyclesActionPerformed(evt);
            }
        });

        btnOpenDbDefault.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDbDefault.setText("Default");
        btnOpenDbDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDbDefaultActionPerformed(evt);
            }
        });

        btnGrp.add(rdoBoth);
        rdoBoth.setSelected(true);
        rdoBoth.setText("Both");
        rdoBoth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoBothActionPerformed(evt);
            }
        });

        btnGrp.add(rdoGluOnly);
        rdoGluOnly.setText("Glu Only");
        rdoGluOnly.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGluOnlyActionPerformed(evt);
            }
        });

        btnGrp.add(rdoGABAOnly);
        rdoGABAOnly.setText("GABA Only");
        rdoGABAOnly.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGABAOnlyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtCycles, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel8)
                        .addGap(18, 18, 18)
                        .addComponent(btnGenRndM2)
                        .addGap(272, 272, 272))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblOpenDatabase)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpenDatabase)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpenDbDefault)
                        .addGap(35, 35, 35)
                        .addComponent(rdoBoth)
                        .addGap(18, 18, 18)
                        .addComponent(rdoGluOnly)
                        .addGap(18, 18, 18)
                        .addComponent(rdoGABAOnly)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOpenDatabase)
                    .addComponent(btnOpenDbDefault)
                    .addComponent(lblOpenDatabase)
                    .addComponent(rdoBoth)
                    .addComponent(rdoGluOnly)
                    .addComponent(rdoGABAOnly))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(txtCycles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnGenRndM2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        statsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        statsPanel.setViewportView(statsTable);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 655, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 393, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(8, 8, 8)
                    .addComponent(statsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(27, Short.MAX_VALUE)))
        );

        jTabbedPane1.addTab("Stats", jPanel3);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 655, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 393, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Details", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void getSimPattCount(int genCycle) {
//        Pattern patt = new Pattern();
//        ArrayList<Integer[]> pattList;
        SummaryStatistics[] sums = new SummaryStatistics[nPattern];
        ConnToIO conns = new ConnToIO(pathToFile);
        conns.init();
        for (int i = 0; i < sums.length; i++) {
            sums[i] = new SummaryStatistics();
        }

        for (int cy = 0; cy < genCycle; cy++) {
            Double patCount[] = conns.getExpDist(type);
            for (int i = 0; i < nPattern; i++) {
                try {
                    double value = patCount[i];
                    sums[i].addValue(value);
                } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
                }
            }
        }
        double exp[];
        double prob[];
        exp = new double[obs.length];
        prob = new double[obs.length];

        Object[][] sumsTable = new Object[nPattern + 1][5];
        sumsTable[0][0] = "ID";
        sumsTable[0][1] = "OBS";
        sumsTable[0][2] = "EXP";
        sumsTable[0][3] = "S.D.";
        sumsTable[0][4] = "p";

        for (int i = 0; i < nPattern; i++) {
            int j = i + 1;
            sumsTable[j][0] = new Integer(i);
            sumsTable[j][1] = new Double(obs[i]);
            exp[i] = sums[i].getMean();
            sumsTable[j][2] = new Double(exp[i]);
            sumsTable[j][3] = new Double(sums[i].getStandardDeviation());
            double zScore = (double) (obs[i] - sums[i].getMean()) / sums[i].getStandardDeviation();
            prob[i] = StatisticsConversion.oneTailPvalue(zScore);
            sumsTable[j][4] = new Double(prob[i]);
        }

        MyTableModel transTable = new MyTableModel(sumsTable);
        statsPanel.setColumnHeaderView(null);
        statsTable.setModel(transTable);
    }

    private void getActualPattCount() {
        ConnToIO conns = new ConnToIO(pathToFile);
        Double patCount[] = conns.getObsDist(type);
        nPattern = conns.getMaxIO();
        obs = patCount;

        //Fill Table
        Object[][] sumsTable = new Object[nPattern + 1][2];
        sumsTable[0][0] = "ID";
        sumsTable[0][1] = "OBS";
        for (int i = 0; i < nPattern; i++) {
            int j = i + 1;
            sumsTable[j][0] = new Integer(i);
            sumsTable[j][1] = new Double(obs[i]);
        }
        MyTableModel transTable = new MyTableModel(sumsTable);
        statsPanel.setColumnHeaderView(null);
        statsTable.setModel(transTable);

    }

    private void btnOpenDbDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDbDefaultActionPerformed
        pathToFile = CommonsLib.getDefaultFile();
        File f = new File(pathToFile);
        if (f.exists()) {
            getActualPattCount();
            btnGenRndM2.setEnabled(true);
        }
    }//GEN-LAST:event_btnOpenDbDefaultActionPerformed

    private void btnOpenDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDatabaseActionPerformed
        int returnVal = DataFileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            pathToFile = DataFileChooser.getSelectedFile().getAbsolutePath();
            getActualPattCount();
            btnGenRndM2.setEnabled(true);
        }
    }//GEN-LAST:event_btnOpenDatabaseActionPerformed

    private void txtCyclesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCyclesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCyclesActionPerformed

    private void btnGenRndM2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenRndM2ActionPerformed
        getSimPattCount(Integer.parseInt(txtCycles.getText()));
    }//GEN-LAST:event_btnGenRndM2ActionPerformed

    private void rdoBothActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoBothActionPerformed
        type = 0;
    }//GEN-LAST:event_rdoBothActionPerformed

    private void rdoGluOnlyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGluOnlyActionPerformed
        type = 1;
    }//GEN-LAST:event_rdoGluOnlyActionPerformed

    private void rdoGABAOnlyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGABAOnlyActionPerformed
        type = 2;
    }//GEN-LAST:event_rdoGABAOnlyActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PatternUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PatternUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser DataFileChooser;
    private javax.swing.JButton btnGenRndM2;
    private javax.swing.ButtonGroup btnGrp;
    private javax.swing.JButton btnOpenDatabase;
    private javax.swing.JButton btnOpenDbDefault;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblOpenDatabase;
    private javax.swing.JRadioButton rdoBoth;
    private javax.swing.JRadioButton rdoGABAOnly;
    private javax.swing.JRadioButton rdoGluOnly;
    private javax.swing.JScrollPane statsPanel;
    private transient javax.swing.JTable statsTable;
    private javax.swing.JTextField txtCycles;
    // End of variables declaration//GEN-END:variables
    private String pathToFile;
    private int nPattern;
    private Double obs[];
    private int type = 0;
}
